package gateway

import (
	"bytes"
	"encoding/json"
	"io/ioutil"
	"net/http"
	"time"

	"github.com/sirupsen/logrus"

	"git.internal.yunify.com/benchmark/benchmark/pkg/boot"
	"git.internal.yunify.com/benchmark/benchmark/pkg/gateway"
	"git.internal.yunify.com/benchmark/benchmark/pkg/gateway/grpc_proxy"
	"git.internal.yunify.com/benchmark/benchmark/pkg/global"
	"git.internal.yunify.com/huangyingjun/qingbilling-gateway/api/generate/pb"
	staticSpec "git.internal.yunify.com/huangyingjun/qingbilling-gateway/api/generate/swagger/spec"
	staticSwaggerUI "git.internal.yunify.com/huangyingjun/qingbilling-gateway/api/generate/swagger/swagger-ui"
	"git.internal.yunify.com/huangyingjun/qingbilling-gateway/internal/apps/gateway/router"
	"git.internal.yunify.com/huangyingjun/qingbilling-gateway/internal/constants"
	config2 "git.internal.yunify.com/huangyingjun/qingbilling-gateway/internal/pkg/config"
)

func Start() (err error) {
	go sendSwaggerToYApi()
	//注册rpc服务
	register := map[string][]grpc_proxy.EndpointFun{
		constants.ServiceCooperate: {pb.RegisterNewBillingGatewayManagerHandlerFromEndpoint},
	}

	return boot.NewWebServer(constants.GateWay, constants.GateWayPort, config2.ConfigFilePath()).
		//自定义路由
		WithRouter(router.Router).
		//swaggerUI
		WithOption(gateway.WithStaticSwagger(staticSwaggerUI.Files, staticSpec.Files)).
		//rpc反向代理
		WithRegister(register).

		//Cmd启动
		Run()
}

func sendSwaggerToYApi() {
	time.Sleep(time.Minute)

	if !global.AppConfig().IsStaging() {
		return
	}

	bodyMap := map[string]string{
		"type":  "swagger",
		"json":  staticSpec.Files["api.swagger.json"],
		"merge": "merge",
		"token": "c6fc5ea1bb58d978619cd69114e706affd088cbeceeeb1f3f06a90146dd629e2",
	}

	s, _ := json.Marshal(bodyMap)
	resp, err := http.Post("https://yapi.yunify.com/api/open/import_data", "application/json", ioutil.NopCloser(bytes.NewReader(s)))
	if err != nil {
		logrus.Infof("sendSwaggerToYApi err:%v", err)
	}
	bs, _ := ioutil.ReadAll(resp.Body)

	logrus.Infof("sendSwaggerToYApi result:%s", string(bs))
}
